<template>
  <div class="contract-detail">
    <div class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <h2>客户审核 - 合同详情</h2>
        <!-- 返回按钮（美化） -->
        <button class="btn btn-back" @click="goBack">
          <i class="fa fa-arrow-left mr-2"></i>返回列表
        </button>
      </div>
    </div>

    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载合同详情中...</p>
    </div>
    <div v-else-if="error" class="error-message">
      <i class="fa fa-exclamation-circle mr-2"></i>{{ error }}
    </div>
    <div v-else>
      <div class="contract-info card mb-4">
        <div class="card-header bg-light">
          <h3 class="card-title">合同基本信息</h3>
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-md-6">
              <p><strong>合同ID:</strong> {{ contract.id || contractId || '未提供' }}</p>
              <p><strong>合同名称:</strong> {{ contract.name || '未提供' }}</p>
              <p><strong>项目经理:</strong> {{ contract.projectManagerName || '未提供' }}</p>
            </div>
            <div class="col-md-6">
              <p><strong>客户公司:</strong> {{ contract.customerCompanyName || '未提供' }}</p>
              <p><strong>创建时间:</strong> {{ formatDate(contract.createTime) || '未提供' }}</p>
              <p><strong>状态:</strong> <span :class="getStatusClass(contract.status)">{{ getStatusText(contract.status) }}</span></p>
              <p><strong>待审核条款数:</strong> {{ pendingClausesCount }}</p>
            </div>
          </div>
        </div>
      </div>

      <div class="clauses-section card">
        <div class="card-header bg-light">
          <h3 class="card-title">合同条款 ({{ clauses.length }}条)</h3>
        </div>
        <div class="card-body">
          <div v-if="clauses.length === 0" class="empty-message text-center py-4">
            <i class="fa fa-info-circle text-info mr-2"></i>暂无条款信息
          </div>
          <div class="clauses-list" v-else>
            <div v-for="clause in clauses" :key="clause.id" class="clause-item mb-3 p-3 border rounded">
              <div class="clause-header d-flex justify-content-between align-items-center mb-2">
                <h4 class="clause-title">{{ clause.title || '条款' + (clauses.indexOf(clause) + 1) }}</h4>
                <span :class="getStatusClass(clause.auditStatus)">
                  {{ getClauseStatusText(clause.auditStatus) }}
                </span>
              </div>
              <div class="clause-content mb-3">
                <p>{{ clause.content }}</p>
              </div>
              <div class="clause-actions d-flex justify-content-end">
                <!-- 审核按钮（美化） -->
                <button
                    v-if="clause.auditStatus === 'PENDING'"
                    class="btn btn-audit"
                    @click="auditClause(clause.id)"
                >
                  <i class="fa fa-check mr-1"></i> 审核
                </button>
                <!-- 已审核按钮（美化） -->
                <button
                    v-if="clause.auditStatus !== 'PENDING'"
                    class="btn btn-disabled"
                    disabled
                >
                  <i class="fa fa-lock mr-1"></i> 已审核
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'

export default {
  name: 'CustomerAuditContractDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()

    const contractId = route.params.contractId
    const contract = ref({})
    const clauses = ref([])
    const loading = ref(true)
    const error = ref('')
    const pendingClausesCount = ref(0)

    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      try {
        const date = new Date(dateString)
        return date.toLocaleString()
      } catch (e) {
        console.error('日期格式化失败', e)
        return dateString
      }
    }

    // 获取合同状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 'DRAFT': return '草稿'
        case 'PENDING_REVIEW': return '待审核'
        case 'REVIEW_FAILED': return '审核失败'
        case 'PENDING_CONFIRMATION': return '待确认'
        case 'CONFIRMED': return '已确认'
        case 'COMPLETED': return '已完成'
        case 'ARCHIVED': return '已归档'
        default: return status || '未知'
      }
    }

    // 获取条款审核状态文本
    const getClauseStatusText = (status) => {
      switch (status) {
        case 'PENDING': return '待审核'
        case 'APPROVED': return '已通过'
        case 'REJECTED': return '已拒绝'
        default: return status || '未知'
      }
    }

    // 获取状态样式
    const getStatusClass = (status) => {
      switch (status) {
        case 'DRAFT': return 'badge bg-secondary'
        case 'PENDING_REVIEW': return 'badge bg-info'
        case 'REVIEW_FAILED': return 'badge bg-danger'
        case 'PENDING_CONFIRMATION': return 'badge bg-warning'
        case 'CONFIRMED': return 'badge bg-primary'
        case 'COMPLETED': return 'badge bg-success'
        case 'ARCHIVED': return 'badge bg-dark'
        case 'PENDING': return 'badge bg-warning'
        case 'APPROVED': return 'badge bg-success'
        case 'REJECTED': return 'badge bg-danger'
        default: return 'badge bg-secondary'
      }
    }

    // 审核条款（跳转到条款审核页）
    const auditClause = (clauseId) => {
      router.push(`/customer/audit-clause/${contractId}/${clauseId}`)
    }

    // 获取合同详情
    const fetchContractDetails = () => {
      loading.value = true
      error.value = ''

      if (!contractId) {
        error.value = '合同ID不能为空'
        loading.value = false
        return
      }

      axios.get(`/auth/contracts/${contractId}/customer-audit`, {
        headers: {
          'X-Customer-Id': store.state.user?.id
        }
      })
          .then(response => {
            if (response.data) {
              if (response.data.id) {
                contract.value = response.data
                clauses.value = response.data.clauses || []
              } else if (response.data.contract) {
                contract.value = response.data.contract || {}
                clauses.value = response.data.clauses || []
              } else {
                console.error('API返回结构不符合预期:', response.data)
                error.value = '获取合同详情失败，数据结构异常'
              }
            } else {
              error.value = '获取合同详情失败，无数据返回'
            }

            pendingClausesCount.value = clauses.value.filter(clause => clause.auditStatus === 'PENDING').length
          })
          .catch(err => {
            console.error('获取合同详情失败', err)

            if (err.response) {
              switch (err.response.status) {
                case 401:
                  error.value = '未授权，请重新登录'
                  router.push('/login')
                  break
                case 403:
                  error.value = '您没有权限查看此合同'
                  break
                case 404:
                  error.value = '合同不存在或已被删除'
                  break
                default:
                  error.value = `获取合同详情失败 (${err.response.status})`
              }
            } else {
              error.value = '网络错误，无法获取合同详情'
            }
          })
          .finally(() => {
            loading.value = false
          })
    }

    onMounted(() => {
      fetchContractDetails()
    })

    return {
      contractId,
      contract,
      clauses,
      loading,
      error,
      pendingClausesCount,
      goBack,
      formatDate,
      getStatusText,
      getClauseStatusText,
      getStatusClass,
      auditClause
    }
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.contract-detail {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  background-color: #f8f9fa;
  padding: 15px 20px;
  border-radius: 6px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.header-content {
  width: 100%;
}

/* 基础按钮样式 */
.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.btn i {
  font-size: 14px;
}

/* 按钮交互反馈 */
.btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.btn:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 按钮分类样式 */
/* 1. 返回按钮 */
.btn-back {
  background-color: #6c757d;
  color: #fff;
}

.btn-back:hover:not(:disabled) {
  background-color: #5a6268;
}

/* 2. 审核按钮 */
.btn-audit {
  background-color: #007bff;
  color: #fff;
}

.btn-audit:hover:not(:disabled) {
  background-color: #0069d9;
}

/* 3. 已审核（禁用）按钮 */
.btn-disabled {
  background-color: #6c757d;
  color: #fff;
  opacity: 0.7;
}

/* 加载状态 */
.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  min-height: 300px;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #007bff;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 错误消息 */
.error-message {
  color: #dc3545;
  background-color: #f8d7da;
  padding: 12px 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  border-left: 3px solid #dc3545;
}

/* 卡片样式 */
.card {
  border: none;
  border-radius: 6px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.card-header {
  padding: 12px 20px;
  font-weight: 600;
}

.card-body {
  padding: 20px;
}

/* 条款样式 */
.clause-item {
  border: 1px solid #e9ecef;
  transition: all 0.3s ease;
}

.clause-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-color: #dee2e6;
}

.clause-title {
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 0;
}

/* 状态徽章样式 */
.badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.85em;
  font-weight: 500;
  color: #fff;
}

.bg-secondary { background-color: #6c757d; }
.bg-primary { background-color: #007bff; }
.bg-success { background-color: #28a745; }
.bg-danger { background-color: #dc3545; }
.bg-dark { background-color: #343a40; }
.bg-warning { background-color: #ffc107; }
.bg-info { background-color: #17a2b8; }

/* 空状态样式 */
.empty-message {
  text-align: center;
  padding: 40px 20px;
  background-color: #f8fafc;
  border-radius: 6px;
  border: 1px dashed #e2e8f0;
}

.empty-message i {
  color: #94a3b8;
  margin-bottom: 15px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .row {
    flex-direction: column;
    gap: 15px;
  }

  .col-md-6 {
    width: 100%;
  }
}
</style>